/**
 * 搜索管理器
 */
class SearchManager {
    constructor() {
        this.searchBtn = null;
        this.searchTypeRadios = null;
        this.searchQuery = null;
        this.searchResults = null;
        this.searchResultsContent = null;
        this.enableDedupCheckbox = null;
        this.dedupMultiplierContainer = null;
        this.dedupMultiplierInput = null;
        this.init();
    }

    init() {
        // 确保DOM已加载
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.initializeElements());
        } else {
            this.initializeElements();
        }
    }

    initializeElements() {
        // 延迟获取DOM元素，确保DOM已完全加载
        setTimeout(() => {
            // 获取DOM元素
            this.searchBtn = document.getElementById('searchBtn');
            this.searchTypeRadios = document.querySelectorAll('input[name="searchType"]');
            this.searchQuery = document.getElementById('searchQuery');
            this.searchResults = document.getElementById('searchResults');
            this.searchResultsContent = document.getElementById('searchResultsContent');
            this.enableDedupCheckbox = document.getElementById('enableDedup');
            this.dedupMultiplierContainer = document.getElementById('dedupMultiplierContainer');
            this.dedupMultiplierInput = document.getElementById('dedupMultiplier');

            // 绑定事件
            this.bindEvents();

            // 初始化搜索UI
            this.updateSearchUI();
            this.updateDedupUI();
        }, 100); // 延迟100ms确保DOM已完全加载
    }

    bindEvents() {
        if (this.searchBtn) {
            this.searchBtn.addEventListener('click', (e) => {
                e.preventDefault();
                this.performSearch();
            });
        }

        // 搜索类型切换时更新UI
        if (this.searchTypeRadios) {
            this.searchTypeRadios.forEach(radio => {
                radio.addEventListener('change', () => {
                    this.updateSearchUI();
                });
            });
        }

        // 去重选项切换时更新UI
        if (this.enableDedupCheckbox) {
            this.enableDedupCheckbox.addEventListener('change', () => {
                this.updateDedupUI();
            });
        }
    }

    updateSearchUI() {
        const searchType = document.querySelector('input[name="searchType"]:checked')?.value;
        const thresholdLabel = document.querySelector('label[for="searchThreshold"]');
        
        if (!this.searchQuery || !thresholdLabel) return;

        // 根据搜索类型更新提示文本
        switch(searchType) {
            case 'semantic':
                this.searchQuery.placeholder = '输入您的问题或描述，例如：如何实现文件上传功能？';
                thresholdLabel.textContent = '相似度阈值';
                break;
            case 'regex':
                this.searchQuery.placeholder = '输入正则表达式，例如：func.*Upload';
                thresholdLabel.textContent = '匹配度阈值';
                break;
        }
    }

    updateDedupUI() {
        if (!this.enableDedupCheckbox || !this.dedupMultiplierContainer) return;

        if (this.enableDedupCheckbox.checked) {
            this.dedupMultiplierContainer.classList.remove('hidden');
        } else {
            this.dedupMultiplierContainer.classList.add('hidden');
        }
    }

    async performSearch() {
        const searchType = document.querySelector('input[name="searchType"]:checked')?.value;
        const query = this.searchQuery?.value.trim();
        
        if (!query) {
            this.showAlert('请输入搜索查询');
            return;
        }
        
        const limit = parseInt(document.getElementById('searchLimit')?.value || 10);
        const threshold = parseFloat(document.getElementById('searchThreshold')?.value || 0.5);
        const fileTypes = this.parseFileTypes(document.getElementById('fileTypes')?.value || '');
        const enableDedup = this.enableDedupCheckbox?.checked || false;
        const dedupMultiplier = parseInt(this.dedupMultiplierInput?.value || 100);
        
        this.setSearchButtonLoading(true);
        
        try {
            let response;
            
            // 根据搜索类型调用不同的API
            switch(searchType) {
                case 'semantic':
                    response = await window.apiClient.semanticSearch(
                        query, limit, threshold, fileTypes, [], enableDedup, dedupMultiplier
                    );
                    break;
                case 'keyword':
                    response = await window.apiClient.keywordSearch(
                        query, limit, threshold, fileTypes, false, enableDedup, dedupMultiplier
                    );
                    break;
                case 'regex':
                    response = await window.apiClient.regexSearch(
                        query, limit, threshold, fileTypes, query, enableDedup, dedupMultiplier
                    );
                    break;
                default:
                    throw new Error('未知的搜索类型');
            }
            
            if (response.success) {
                this.displaySearchResults(response.data, searchType);
            } else {
                this.showAlert(`搜索失败: ${response.message}`);
            }
        } catch (error) {
            console.error('Error performing search:', error);
            this.showAlert('搜索失败，请检查服务器连接');
        } finally {
            this.setSearchButtonLoading(false);
        }
    }

    parseFileTypes(fileTypesStr) {
        return fileTypesStr
            .split(',')
            .map(type => type.trim())
            .filter(type => type.length > 0);
    }

    setSearchButtonLoading(loading) {
        if (!this.searchBtn) return;

        if (loading) {
            this.searchBtn.disabled = true;
            this.searchBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>搜索中...';
        } else {
            this.searchBtn.disabled = false;
            this.searchBtn.innerHTML = '<i class="fas fa-search mr-2"></i>搜索';
        }
    }

    displaySearchResults(results, searchType) {
        if (!this.searchResults || !this.searchResultsContent) return;

        this.searchResults.classList.remove('hidden');
        
        if (!results.results || results.results.length === 0) {
            this.searchResultsContent.innerHTML = '<p class="text-gray-600">未找到匹配的结果</p>';
            return;
        }
        
        // 按相似度从高到低排序
        const sortedResults = [...results.results].sort((a, b) => b.score - a.score);
        
        let resultsHtml = this.buildSearchStatistics(results);
        resultsHtml += this.buildSearchResultsHtml(sortedResults, results, searchType);
        
        this.searchResultsContent.innerHTML = resultsHtml;
    }

    buildSearchStatistics(results) {
        let statsHtml = `
            <div class="mb-4 text-sm text-gray-600">
                找到 ${results.total} 个结果，耗时 ${results.took} 毫秒
            </div>
        `;
        
        // 如果启用了去重归纳，显示额外信息
        if (results.enable_dedup && results.original_count > 0) {
            statsHtml += `
                <div class="mb-4 text-sm text-blue-600">
                    <i class="fas fa-info-circle mr-1"></i>
                    已启用结果文件去重归纳，原始检索 ${results.original_count} 条结果，去重后返回 ${results.total} 个唯一文件
                </div>
            `;
        }
        
        return statsHtml;
    }

    buildSearchResultsHtml(sortedResults, results, searchType) {
        return sortedResults.map(result => {
            let formattedContent = this.formatContent(result.content, results.query, searchType, result.highlight);
            
            // 限制内容长度
            if (formattedContent.length > 300) {
                formattedContent = formattedContent.substring(0, 300) + '...';
            }
            
            // 提取匹配次数（如果存在）
            let matchCountInfo = '';
            if (results.enable_dedup && result.content && result.content.startsWith('[匹配次数:')) {
                const matchCount = this.extractMatchCount(result.content);
                if (matchCount > 1) {
                    matchCountInfo = `<span class="ml-2 px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full">匹配 ${matchCount} 次</span>`;
                }
                // 从内容中移除匹配次数前缀
                formattedContent = formattedContent.replace(/^\[匹配次数: \d+\]\s*/, '');
            }
            
            // 格式化文件大小
            let fileSizeInfo = '';
            if (result.file_size !== undefined && result.file_size !== null) {
                fileSizeInfo = this.formatFileSize(result.file_size);
            }
            
            return `
                <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
                    <div class="flex justify-between items-start mb-2">
                        <h5 class="font-bold text-gray-800">${result.file_name}</h5>
                        <div class="flex items-center">
                            <span class="text-sm text-gray-500">相似度: ${(result.score * 100).toFixed(1)}%</span>
                            ${matchCountInfo}
                        </div>
                    </div>
                    <p class="text-sm text-gray-600 mb-2">路径: <a href="#" class="text-blue-600 hover:text-blue-800 hover:underline file-path-link" 
                        data-file-path="${result.file_path}" 
                        data-chunk-id="${result.chunk_id}" 
                        data-start-pos="${result.start_pos}" 
                        data-end-pos="${result.end_pos}" 
                        data-start-line="${result.start_line || 1}" 
                        data-end-line="${result.end_line || 1}">${result.file_path || '未知'}</a></p>
                    <div class="bg-gray-50 p-3 rounded mb-2">
                        <pre class="whitespace-pre-wrap text-sm text-gray-700">${formattedContent}</pre>
                    </div>
                    <div class="flex justify-between text-xs text-gray-500">
                        <span>分块: ${result.chunk_no}</span>
                        <div>
                            <span>位置: ${result.start_pos}-${result.end_pos} (行 ${result.start_line || 1}-${result.end_line || 1})</span>
                            ${fileSizeInfo ? `<span class="ml-3">大小: ${fileSizeInfo}</span>` : ''}
                        </div>
                    </div>
                </div>
            `;
        }).join('');
    }

    formatContent(content, query, searchType, highlight) {
        let formattedContent = content;
        
        if (searchType === 'regex') {
            // 正则匹配高亮
            if (highlight) {
                formattedContent = highlight;
            }
        }
        
        return formattedContent;
    }

    escapeRegExp(str) {
        return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }

    extractMatchCount(content) {
        // 使用正则表达式提取匹配次数
        const match = content.match(/^\[匹配次数: (\d+)\]/);
        if (match && match[1]) {
            return parseInt(match[1]);
        }
        return 1;
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    showAlert(message) {
        alert(message);
    }
}

// 创建全局搜索管理器实例
window.searchManager = new SearchManager();